import requests
from datetime import datetime
from sensor.frame import Frame
from fileOP.filePack import FilePack


class ClientAPI:
    def __init__(self):
        self.url = None

    def TestConnection(self, url: str) -> bool:
        try:
            response = requests.get(url + "/test")
        except:
            self.url = None
            return False
        print("test response status code:", response.status_code)
        if response.status_code == 200:
            self.url = url
            return True

    def GetTags(self) -> list[str]:
        if self.url is None:
            return []
        try:
            response = requests.get(self.url + "/sensor")
        except:
            return []
        print("tags response status code:", response.status_code)
        if response.status_code != 200:
            print(response.status_code, response.text)
            return []
        return response.text.split(",")

    def GetServerInfo(self) -> str:
        if self.url is None:
            return None
        try:
            response = requests.get(self.url + "/info")
        except:
            return False
        print("info response status code:", response.status_code)
        if response.status_code != 200:
            print(response.status_code, response.text)
            return "Error request"
        return response.text

    def GetFrames(
        self, tag: str, startTime: datetime, endTime: datetime, dataType: str
    ) -> list[Frame]:
        if self.url is None:
            return []
        if dataType not in ["raw", "post"]:
            print("Invalid data type")
            return []
        params = {
            "startTime": startTime.strftime("%Y_%m_%d_%H_%M"),
            "endTime": endTime.strftime("%Y_%m_%d_%H_%M"),
            "type": dataType,
            "tag": tag,
        }
        try:
            response = requests.get(self.url + "/data", params=params)
        except:
            return False
        print("response status code:", response.status_code)
        if response.status_code != 200:
            print(response.status_code, response.text)
            return []
        print("received data length:", len(response.content))
        filesBytes = FilePack.Unpack(response.content)

        allFrames = []
        for fileBytes in filesBytes:
            # each fileBytes is a file of Frames in minutes
            content = fileBytes.decode("utf-8")
            framestrList = content.split("\n")
            for framestr in framestrList:
                if framestr == "":
                    continue
                newFrame = Frame()
                newFrame.DecodeFromString(framestr)
                allFrames.append(newFrame)
        return allFrames


if __name__ == "__main__":
    clientAPI = ClientAPI("http://localhost:5000")
    print(clientAPI.TestConnection())
    print(clientAPI.GetServerInfo())
    print(clientAPI.GetTags())
    frames = clientAPI.GetFrames(
        "Sensor6", datetime(2024, 7, 12, 17, 55), datetime(2024, 7, 12, 18, 5), "raw"
    )
    for frame in frames:
        print(frame)
